//
//  AppDelegate+ThirdPart.m
//  HaoLyyPro
//
//  Created by Guanghui Liao on 12/13/17.
//  Copyright © 2017 jk. All rights reserved.
//

#import "AppDelegate+ThirdPart.h"
//#import "JKStartVC.h"
#import <UMMobClick/MobClick.h>
#import <UMSocialCore/UMSocialCore.h>
#import "Factory.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
@implementation UIResponder (ThirdPart)

// 配置根控制器
- (void)setNewFeatureVCWithWindow:(UIWindow *)window andRootVC:(UITabBarController *)rootVC{
   // 判断是否登陆过,用当前版本号做Key来存储版本号
    BOOL userHasOnboarded = [[NSUserDefaults standardUserDefaults] boolForKey:[Factory VersonString]];
    
    if (userHasOnboarded) {
        window.rootViewController = rootVC;
        
    } else {
        window.rootViewController = rootVC;

//        JKStartVC* vc= [[JKStartVC alloc]init];
//        vc.delegate=[RACSubject subject];
//        [vc.delegate subscribeNext:^(id x) {
//            window.rootViewController = rootVC;
//            [Factory setUserDefoultWithBool:YES forkey:[Factory VersonString]];
//        }];
//        window.rootViewController = vc;
    }
}
//配置IQKeyBoard
-(void)addIQKeyBoard{
    IQKeyboardManager *manager=[IQKeyboardManager sharedManager];
    manager.enable=YES;
    manager.shouldShowTextFieldPlaceholder=YES;
    manager.shouldResignOnTouchOutside=YES;
    manager.enableAutoToolbar=NO;
}
//版本控制
-(void)addAutoRemotes{
//    [[AppGlobalDataCenter defaultCenter] requestAppVersion];
}


//友盟统计
- (void)configUmengAnalytics{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
#warning TODO
    UMConfigInstance.appKey = @"UMEN_KEY";
#if kProductionEnvironment
    UMConfigInstance.channelId = @"App Store";
#else
    UMConfigInstance.channelId = @"TestIOS";
    
#endif
    
    [MobClick startWithConfigure:UMConfigInstance];
    [MobClick setLogEnabled:NO];
}
//友盟分享
- (void)confitUShareSettings{
    //设置友盟分享
#warning TODO
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"UMEN_KEY"];

    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"TODO" appSecret:@"TODO" redirectURL:nil];
    /* 设置QQ的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"TODO"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
}

//个推
- (void)addGetuiSDK{
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:@"TODO" appKey:@"TODO" appSecret:@"TODO" delegate:self];
    //注册 APNs
    [self registerRemoteNotification];
    [GeTuiSdk resetBadge]; //重置角标计数
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

#pragma mark- 个推的各种代理
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
#warning TODO
//    [AppGlobalDataCenter defaultCenter].geTuiCID = clientId;
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // 页面显示：上行消息结果反馈
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
}

//个推的消息系统
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    if ([UIApplication sharedApplication].applicationIconBadgeNumber==0) {
        UIAlertController* alert=[UIAlertController alertControllerWithTitle:nil message:@"您有一条新消息" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction* action=[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action];
        
//        [self.rootVC presentViewController:alert animated:YES completion:^{
//
//        }];
    }
    [Factory setUserDefoultWithBool:YES forkey:@"NewMessage"];
#warning TODO
//    [(GHHomeVC*)((RTRootNavigationController*)self.rootVC.viewControllers[0]).rt_viewControllers[0] createRightBtn];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //    [alert addAction:[UIAlertAction actionWithTitle:@"前往查看" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    //        ///用户点击推送跳转到消息中心
    //        [self.rootVC pushViewController:[JKMsgCenterVC new] animated:YES];
    //    }]];
    
}


/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

#pragma mark- 系统方法移植过来

/*

//获取苹果的推送token传给getui
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}
 */

#pragma mark - iOS 10中收到推送消息

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    //    if (![self currentVCIsMSGCenter]) {
    //        UIAlertController* alert=[UIAlertController alertControllerWithTitle:nil message:@"您有一条新消息" preferredStyle:(UIAlertControllerStyleAlert)];
    //        UIAlertAction* action=[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    //        }];
    //        [alert addAction:action];
    //        [alert addAction:[UIAlertAction actionWithTitle:@"前往查看" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    //            [self.rootVC pushViewController:[JKMsgCenterVC new] animated:YES];
    //        }]];
    //        [self.rootVC presentViewController:alert animated:YES completion:^{
    //
    //        }];
    //    }
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发  后台或者关闭app 点击通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    ///用户点击推送跳转到消息中心
    //    if (![self currentVCIsMSGCenter]) {
    //        [self.rootVC pushViewController:[JKMsgCenterVC new] animated:YES];
    //    }
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    completionHandler();
}
#endif

#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送
/** APP已经接收到“远程”通知(推送) - (App运行在后台运行时候收到推送会走这个方法)   */
/*
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    
    // 显示APNs信息到页面
    NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], userInfo];
    DLog(@"%@",record);
    //    [_viewController logMsg:record];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    completionHandler(UIBackgroundFetchResultNewData);
}
 */

@end
